package cn.net.asiacom.extrator.extra;


import cn.net.asiacom.entity.NewInvoice;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 发票操作类
 * 新版发票操作类（NewInvoiceExtractor）
 */
public class NewInvoiceExtractor {

    private static final String PDF_EXTENSION = ".pdf";
    /**
     * 检查文件是否为PDF文件
     *
     * @param file 要检查的文件
     * @return 如果是PDF文件，返回 true，否则返回 false
     */
    private static boolean isPdfFile(File file) {
        return file.isFile() && file.getName().toLowerCase().endsWith(PDF_EXTENSION);
    }
    /**
     * 处理提取失败的情况，输出错误信息
     *
     * @param file 提取失败的文件
     */
    private static void handleExtractionError(File file) {
        throw new RuntimeException("文件: " + file.getName() + "\t提取失败");
    }


    /**
     * 从本地文件或URL中提取发票信息。
     *
     * @param filePath 本地文件路径或发票的URL。
     * @return 包含提取信息的 NewInvoice 对象。
     */
    public static NewInvoice extractInvoice(String filePath) {
        File pdfFile = new File(filePath);

        if (!pdfFile.exists()) {
            throw new RuntimeException("指定的源文件不存在");
        }
        if (!isPdfFile(pdfFile)) {
            throw new RuntimeException("指定的源文件不是PDF文件");
        }

        NewInvoice result = null;
        try {
            result = NewPdfInvoiceExtractor.extract(pdfFile);
            result.setFileAbsolutePath(pdfFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            result = new NewInvoice();
        }
        return result;
    }

    /**
     * 处理指定文件夹中的PDF发票文件
     * @param folderPath 文件夹路径
     * @return 包含提取信息的 NewInvoice 列表
     */
    private static List<NewInvoice> newPdfProcessInvoicesInFolder(String folderPath) {
        File folder = new File(folderPath);
        File[] files = folder.listFiles();
        List<NewInvoice> resultList = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                if (isPdfFile(file)) {
                    NewInvoice result = extractInvoice(file.getAbsolutePath());
                    if (result != null) {
                        NewInvoice returnResult = createProcessedInvoice(result);
                        resultList.add(returnResult);
                    } else {
                        handleExtractionError(file);
                    }
                }
            }
        }
        return resultList;
    }

    /**
     * 处理指定的PDF发票文件
     * @param filePath 文件路径
     * @return 包含提取信息的 NewInvoice 列表
     */
    private static NewInvoice newPdfProcessInvoicesInFile(String filePath) {
        File file = new File(filePath);
        NewInvoice returnResult = new NewInvoice();
        if (isPdfFile(file)) {
            NewInvoice result = extractInvoice(file.getAbsolutePath());
            if (result != null) {
                returnResult = createProcessedInvoice(result);
            } else {
                handleExtractionError(file);
            }
        }
        return returnResult;
    }

    /**
     * 创建一个处理后的 NewInvoice 对象
     * @param result 原始的 NewInvoice 对象
     * @return 处理后的 NewInvoice 对象
     */
    private static NewInvoice createProcessedInvoice(NewInvoice result) {
        NewInvoice returnResult = new NewInvoice();
        returnResult.setFileAbsolutePath(result.getFileAbsolutePath());
        returnResult.setNumber(result.getNumber());
        returnResult.setDate(result.getDate());
        returnResult.setTotalAmount(result.getTotalAmount());
        returnResult.setAmount(result.getAmount());
        returnResult.setTaxAmount(result.getTaxAmount());
        returnResult.setSellerName(result.getSellerName());
        return returnResult;
    }

    /**
     * 输出发票提取内容
     * @param invoiceList 发票提取结果集合
     */
    private static void newPrintListInvoice(List<NewInvoice> invoiceList, String type){
        int sum = 0;
        for (NewInvoice invoice : invoiceList) {
            sum++;
            if ("String".equals(type) || "string".equals(type)){
                System.out.println("\n文件绝对路径: " + invoice.getFileAbsolutePath() +
                                   "\n发票号码: " + invoice.getNumber() +
                                   "\n开票日期: " + invoice.getDate() +
                                   "\n总价: " + invoice.getTotalAmount() +
                                   "\n金额: " + invoice.getAmount() +
                                   "\n税额: " + invoice.getTaxAmount() +
                                   "\n销售方名称: " + invoice.getSellerName());
            } else if ("List".equals(type) || "list".equals(type)) {
                System.out.println(invoice);
            } else {
                System.out.println(invoice);
            }
        }
        System.out.println("\nTotal:" + sum);
    }

}